package com.gelpag.base.tools;

import been.RoleInfo;
import entity.Const;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;

public class CommonUtil {

    /**
     * 返回登录人的权限，有优先级的
     *
     * @param roleInfos
     * @return 0:admin,1:管理员，2：入驻业主，3：没登录
     */
    public static String getRoleRange(List<RoleInfo> roleInfos) {

        String admin = "admin";
        String gly_role = ParamCacheUtil.getParamValue(Const.REDIS_HEAD_OPERATION + "_" + Const.REDIS_PARAM + "_" + "sisp_creat_gly_role");
        String unit_role = ParamCacheUtil.getParamValue(Const.REDIS_HEAD_OPERATION + "_" + Const.REDIS_PARAM + "_" + "sisp_creat_unit_role");
        if (roleInfos != null && roleInfos.size() > 0) {
            for (RoleInfo roleInfo : roleInfos) {
                if (admin.equals(roleInfo.getRole_id())) {
                    return "0";
                } else if (gly_role.equals(roleInfo.getRole_id())) {
                    return "1";
                } else if (unit_role.equals(roleInfo.getRole_id())) {
                    return "2";
                }
            }
        }

        return "3";
    }

    public static String MD5Encrypt(String inStr) {
        MessageDigest md = null;
        String outStr = null;
        try {
            md = MessageDigest.getInstance("MD5"); // 可以选中其他的算法如SHA
            byte[] digest = md.digest(inStr.getBytes());
            // 返回的是byet[]，要转化为String存储比较方便
            outStr = bytetoString(digest);
        } catch (NoSuchAlgorithmException nsae) {
            nsae.printStackTrace();
        }
        return outStr;
    }

    public static String bytetoString(byte[] digest) {

        String str = "";
        String tempStr = "";
        for (int i = 1; i < digest.length; i++) {
            tempStr = (Integer.toHexString(digest[i] & 0xff));
            if (tempStr.length() == 1) {
                str = str + "0" + tempStr;
            } else {
                str = str + tempStr;
            }
        }
        return str.toLowerCase();
    }
}
